package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.enums.HcSyncMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.utils.HcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商家订单
 * @Author: jeecg-boot
 * @Date: 2022-12-20
 * @Version: V1.0
 */
@Api(tags = "商家订单")
@RestController
@RequestMapping("/hc/hcOrderMerchant")
@Slf4j
public class HcOrderMerchantController extends JeecgController<HcOrderMerchant, IHcOrderMerchantService> {

    @Autowired
    private IHcCompanyPickupAddressService companyPickupAddressService;
    @Autowired
    private IHcOrderMerchantService hcOrderMerchantService;
    @Autowired
    private IHcCompanyMerchantSettingService companyMerchantSettingService;
    @Autowired
    private IHcCompanyInfoService hcCompanyInfoService;

    @Autowired
    private IHcMerchantService hcMerchantService;

    @Autowired
    private IHcMerchantSettlementService hcMerchantSettlementService;

    @Autowired
    private IHcCompanyFoodOrderService hcCompanyFoodOrderService;


    @Lazy
    @Autowired
    private IHcOrderService hcOrderService;



    @Autowired
    private IHcWxPayRefundService hcWxPayRefundService;


    @Autowired
    private IHcAliRefundService hcAliRefundService;


    @AutoLog(value = "取消订单")
    @ApiOperation("取消订单")
    @GetMapping("/cancelOrder")
    public Result<?> cancelOrder(@RequestParam String id) throws WxPayException, AlipayApiException {
        hcOrderMerchantService.cancelOrder(id);
        return Result.ok();
    }

    @ApiOperation("获取商家有效订单")
    @GetMapping(value = "/getOrderListByMerchant")
    public Result<?> getOrderListByMerchant(HcOrderMerchant param,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        param.setMerchantId(sysUser.getId());

        Date parse = DateUtils.parseDate(param.getTimeBegin(), "yyyy年MM月dd日");
        String beginTime = "";
        String endTime = DateUtils.formatDate(parse, "yyyy-MM-dd") + " 18:00:00";

        Calendar instance = Calendar.getInstance();
        instance.setTime(parse);
        instance.add(Calendar.DAY_OF_MONTH, -1);
        beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";

        param.setTimeBegin(beginTime);
        param.setTimeEnd(endTime);

        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        IPage<HcOrderMerchant> pageList = hcOrderMerchantService.getOrderListByMerchantId(page, param);

        for (HcOrderMerchant record : pageList.getRecords()) {
            hcOrderMerchantService.setInformation(record);
        }

        return Result.OK(pageList);
    }

    @ApiOperation("获取概况")
    @PostMapping("/getStatisticsList")
    public Result<?> getStatisticsList(@RequestBody Map param) {
        return Result.ok(hcOrderMerchantService.getStatisticsList(param));
    }

    @ApiOperation("获取全局页面的订单统计信息")
    @GetMapping("/getOrderStatisticsOfGlobalPage")
    public Result<?> getOrderStatisticsOfGlobalPage() {
        JSONObject yongShanTuanTime = HcUtils.getYongShanTuanTime();
        return Result.ok(hcOrderMerchantService.getOrderStatisticsOfGlobalPage(yongShanTuanTime.getString("beginTime"), yongShanTuanTime.getString("endTime")));
    }

    @ApiOperation("查询全局端数据")
    @PostMapping("/queryGlobalData")
    public Result<?> queryGlobalData(@RequestBody JSONObject param) {
        return Result.ok(hcOrderMerchantService.queryGlobalData(param));
    }

    @ApiOperation("获取全局页面订单列表")
    @GetMapping("/getOrderListOfGlobalPage")
    public Result<?> getOrderListOfGlobalPage(HcOrderMerchant param,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        JSONObject yongShanTuanTime = HcUtils.getYongShanTuanTime();
        param.setTimeBegin(yongShanTuanTime.getString("beginTime"));
        param.setTimeEnd(yongShanTuanTime.getString("endTime"));

        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        return Result.ok(hcOrderMerchantService.getOrderListOfGlobalPage(page, param));
    }

    @ApiOperation("获取全局页面商家统计数据")
    @GetMapping("/getMerchantDataListGlobalPage")
    public Result<?> getMerchantDataListGlobalPage(@RequestParam String merchantId) {
        return Result.ok(hcOrderMerchantService.getOrderStatistics(merchantId));
    }

    @ApiOperation("获取全局页面商户端订单页面的订单列表")
    @GetMapping("/getOrderListByMerchantIdGlobalPage")
    public Result<?> getOrderListByMerchantIdGlobalPage(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        @RequestParam String merchantId) {
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        return Result.ok(hcOrderMerchantService.getOrderListByMerchantId(page, merchantId));
    }

    @ApiOperation("获取商家端-数据-收入总额")
    @GetMapping("/getMerchantDataTotalIncome")
    public Result<?> getMerchantDataTotalIncome() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        try {
            hcMerchantSettlementService.syncMerchantSettlement(sysUser.getId(), HcSyncMerchantSettlementTypeEnum.TODAY);
        } catch (Exception e) {
            log.error("getMerchantDataTotalIncome_syncMerchantSettlement error，商户ID：{}", sysUser.getId());
            e.printStackTrace();
        }

        HcMerchant hcMerchant = hcMerchantService.getById(sysUser.getId());

//        HcOrderMerchant hcOrderMerchant = hcOrderMerchantService.getOne(new QueryWrapper<HcOrderMerchant>()
//                .select("ifnull(sum(COMMODITY_PRICE), 0) as TOTAL_PRICE")
//                .eq("MERCHANT_ID", sysUser.getId())
//                .in("STATE", HcOrderStateEnum.PAY.getValue(), HcOrderStateEnum.COMPLETED.getValue())
//        );
//
//        HcAfterSales hcAfterSales = hcAfterSalesService.getOne(new QueryWrapper<HcAfterSales>()
//                .select("ifnull(sum(DEDUCT_MERCHANT_AMOUNT), 0) as DEDUCT_MERCHANT_AMOUNT")
//                .eq("MERCHANT_ID", sysUser.getId())
//                .eq("STATE", HcAfterSalesStateEnum.YES.getValue())
//        );

        HcMerchantSettlement hcMerchantSettlement = hcMerchantSettlementService.getOne(new QueryWrapper<HcMerchantSettlement>()
                .select("ifnull(sum(if(TYPE in ('unsettled','settling','fail'), SETTLEMENT_AMOUNT, 0)), 0) as 'SETTLEMENT_AMOUNT'")
                .eq("MERCHANT_ID", sysUser.getId())
        );
        final BigDecimal[] settlementAmount = {hcMerchantSettlement.getSettlementAmount()};
        //找到未结算的订单
        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, sysUser.getId())
                        .in(HcMerchantSettlement::getType, Arrays.asList(
                                HcMerchantSettlementTypeEnum.UNSETTLED
                                ,HcMerchantSettlementTypeEnum.SETTLING
                                ,HcMerchantSettlementTypeEnum.FAIL))
                        .orderByDesc(HcMerchantSettlement::getSettlementDate)
        );
        //遍历订单找到需要减去的金额
//        final BigDecimal[] finalSettlementAmount = {new BigDecimal(0)};
//        list.forEach( l -> {
//            if (l.getSettlementDate() != null){
//                String beginTime = "";
//                String endTime = "";
//                Calendar instance = Calendar.getInstance();
//                instance.setTime(l.getSettlementDate());
//                beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";
//                instance.add(Calendar.DAY_OF_MONTH, +1);
//                endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:00";
//                //根据id查询售后信息
//                List<HcAfterSales> list1 = hcAfterSalesService.list(
//                        new LambdaQueryWrapper<HcAfterSales>()
//                                .eq(HcAfterSales::getMerchantId, sysUser.getId())
//                                .between(HcAfterSales::getCreateTime,beginTime,endTime)
//                );
//                if (list1!=null){
//                    list1.forEach( l1 -> {
//                        if (l1.getDeductMerchantAmount() != null)
//                            finalSettlementAmount[0] =  finalSettlementAmount[0].add(l1.getDeductMerchantAmount());
//                    });
//                }
//            }
//        });
//        hcMerchant.setTotalIncome(settlementAmount[0].subtract(finalSettlementAmount[0]));
        hcMerchant.setTotalIncome(settlementAmount[0]);
        return Result.ok(hcMerchant);
    }

    @ApiOperation("获取商家端-数据-列表")
    @GetMapping("/getMerchantDataList")
    public Result<?> getMerchantDataList() throws ParseException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(hcOrderMerchantService.getMerchantDataList(sysUser.getId()));
    }

    @ApiOperation("获取商户端订单页面的订单列表")
    @GetMapping("/getOrderListByMerchantId")
    public Result<?> getOrderListByMerchantId(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        return Result.ok(hcOrderMerchantService.getOrderListByMerchantId(page, sysUser.getId()));
    }

    @ApiOperation("获取商户端订单页面的统计信息")
    @GetMapping("/getOrderStatistics")
    public Result<?> getOrderStatistics() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(hcOrderMerchantService.getOrderStatistics(sysUser.getId()));
    }

    @ApiOperation("根据地址id获取下单列表")
    @GetMapping("/getListByAddress")
    public Result<?> getListByAddress(HcOrderMerchant hcOrder,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        return Result.ok(hcOrderMerchantService.getListByAddress(page, hcOrder));
    }

    @ApiOperation("获取当前用户的订单列表")
    @GetMapping(value = "/getList")
    public Result<IPage<HcOrderMerchant>> getList(HcOrderMerchant hcOrder,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcOrder.setUserId(sysUser.getId());
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        IPage<HcOrderMerchant> pageList = hcOrderMerchantService.getList(page, hcOrder);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hcOrderMerchant
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "商家订单-分页列表查询")
    @ApiOperation(value = "商家订单-分页列表查询", notes = "商家订单-分页列表查询")
    @GetMapping(value = "/listNew")
    public Result<IPage<HcOrderMerchant>> queryPageListNew(HcOrderMerchant hcOrderMerchant,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
//        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        if (StringUtils.isNotBlank(hcOrderMerchant.getTimeBegin()) && hcOrderMerchant.getTimeBegin().length() == 16) {
            hcOrderMerchant.setTimeBegin(hcOrderMerchant.getTimeBegin() + ":00");
        }
        if (StringUtils.isNotBlank(hcOrderMerchant.getTimeEnd()) && hcOrderMerchant.getTimeEnd().length() == 16) {
            hcOrderMerchant.setTimeEnd(hcOrderMerchant.getTimeEnd() + ":00");
        }
//        hcOrderMerchantService.pageList(page, hcOrderMerchant);
        IPage<HcOrderMerchant> hcOrderMerchantIPage = hcOrderMerchantService.pageList(page, hcOrderMerchant);
        List<HcOrderMerchant> hcOM = new ArrayList<>(hcOrderMerchantIPage.getRecords());
//        List<HcOrderMerchant> hcOM = (List<HcOrderMerchant>) redisUtil.get(RedisConstant.HC_ORDER_ALL);
//        if (CollectionUtils.isEmpty(hcOM)){
//            hcOM = hcOrderMerchantService.list(new LambdaQueryWrapper<>(hcOrderMerchant));
//            redisUtil.set(RedisConstant.HC_ORDER_ALL,hcOM);
//        }

        //获取企业订单信息
        List<String> orderNums = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                .between(HcCompanyFoodOrder::getCreateTime,hcOrderMerchant.getTimeBegin() + ":00",hcOrderMerchant.getTimeEnd() + ":00"))
                .stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());

        List<HcOrderMerchant> companyOrder = new ArrayList<>();
        for (String orderNum : orderNums) {
            HcOrderMerchant h = new HcOrderMerchant();
            List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
            List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum)
                    .eq(HcCompanyFoodOrder::getMerchantId,hcOrderMerchant.getMerchantId()));
            HcCompanyInfo hcCompanyInfo = hcCompanyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrders.get(0).getCompanyId()));
            h.setCompanyName(hcCompanyInfo.getCompanyName());

            HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
            List<String> foodName = new ArrayList<>();
            //价格
            BigDecimal foodPrice = new BigDecimal(0);
            //合作价格
            BigDecimal coopPrice = new BigDecimal(0);
            for (HcCompanyFoodOrder hcCompanyFoodOrder : companyFoodOrders) {
                h.setState(hcCompanyFoodOrder.getState());
                HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcCompanyFoodOrder.getMerchantId()));
                h.setStoreName(hcMerchant.getStoreName());
                h.setCreateTime(hcCompanyFoodOrder.getCreateTime());
                //地址
                String pickupAddressId = hcCompanyFoodOrder.getPickupAddressId();
                HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                h.setSupplyAddress(pickupAddress.getAddressCode());
                //取餐号
                h.setPickingSerialNo(hcCompanyFoodOrder.getPickingSerialNo());
                h.setNameTakingMeal(hcCompanyFoodOrder.getUsername());
                h.setSupplyAddress(pickupAddress.getAddressCode());
                JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
                JSONObject foodObject = foodInfo.getJSONObject("food");
                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                //商品数量
                int foodNum = (int) foodInfo.get("foodNum");
                // 获取 foodsSpecification 列表
                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                // 将 JSONArray 转换为 List<String>
                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                if (foodsSpecificationArray!=null){
                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                    List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                    foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
                }else {
                    foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
                }
                if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                    //获取门店价格
                    HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                            .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                            .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                    if (null == companyMerchantSetting){
                        companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                    }
                    if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                        //获取企业合作价格
                        foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice());
                        coopPrice = coopPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
                    }else {
                        foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice());
                        coopPrice = coopPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
                    }
                }else {
                    foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice());
                    coopPrice = coopPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
                }
            }
            hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
            h.setNameDishes(Joiner.on("+").join(foodName));
            hcOrderDetailedLists.add(hcOrderDetailed);
            h.setCommodityPrice(foodPrice);
            h.setTotalPrice(coopPrice);
            h.setHcOrderDetailedList(hcOrderDetailedLists);
            companyOrder.add(h);
        }
        if (StringUtils.isNotBlank(hcOrderMerchant.getStoreName())){
            List<HcOrderMerchant> collect = companyOrder.stream().filter(c -> c.getCompanyName().contains(hcOrderMerchant.getStoreName())
                    || c.getStoreName().contains(hcOrderMerchant.getStoreName())
                    || c.getNameDishes().contains(hcOrderMerchant.getStoreName())
                    || c.getNameTakingMeal().contains(hcOrderMerchant.getStoreName())).collect(Collectors.toList());
            hcOM.addAll(collect);
        }else {
            hcOM.addAll(companyOrder);
        }
        hcOM.sort(new Comparator<HcOrderMerchant>() {
            @Override
            public int compare(HcOrderMerchant o1, HcOrderMerchant o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });

//        int totalRecords = (int) (hcOrderMerchantIPage.getTotal()+orderNums.size()); // 计算总记录数
//        // 创建一个 Page 对象，并设置总记录数、每页记录数、当前页数
//        IPage<HcOrderMerchant> pageList = new Page<>(pageNo, pageSize, totalRecords);
//        // 计算分页起始索引和结束索引
//        int startIndex = (pageNo - 1) * pageSize;
//        int endIndex = Math.min(startIndex + pageSize, hcOM.size());
//        // 截取需要的分页数据
//        List<HcOrderMerchant> pageData = hcOM.subList(0, 9);
        // 设置分页数据
        hcOrderMerchantIPage.setRecords(hcOM);
        hcOrderMerchantIPage.setTotal(hcOrderMerchantIPage.getTotal()+orderNums.size());
        return Result.OK(hcOrderMerchantIPage);
    }


    /**
     * 分页列表查询
     *
     * @param hcOrderMerchant
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "商家订单-分页列表查询")
    @ApiOperation(value = "商家订单-分页列表查询", notes = "商家订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcOrderMerchant>> queryPageList(HcOrderMerchant hcOrderMerchant,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcOrderMerchant> page = new Page<>(pageNo, pageSize);
        if (StringUtils.isNotBlank(hcOrderMerchant.getTimeBegin()) && hcOrderMerchant.getTimeBegin().length() == 16) {
            hcOrderMerchant.setTimeBegin(hcOrderMerchant.getTimeBegin() + ":00");
        }
        if (StringUtils.isNotBlank(hcOrderMerchant.getTimeEnd()) && hcOrderMerchant.getTimeEnd().length() == 16) {
            hcOrderMerchant.setTimeEnd(hcOrderMerchant.getTimeEnd() + ":00");
        }
        return Result.OK(hcOrderMerchantService.pageList(page,hcOrderMerchant));
    }

    /**
     * 添加
     *
     * @param hcOrderMerchant
     * @return
     */
    @AutoLog(value = "商家订单-添加")
    @ApiOperation(value = "商家订单-添加", notes = "商家订单-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcOrderMerchant hcOrderMerchant) {
        hcOrderMerchantService.save(hcOrderMerchant);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcOrderMerchant
     * @return
     */
    @AutoLog(value = "商家订单-编辑")
    @ApiOperation(value = "商家订单-编辑", notes = "商家订单-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcOrderMerchant hcOrderMerchant) {
        hcOrderMerchantService.updateById(hcOrderMerchant);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商家订单-通过id删除")
    @ApiOperation(value = "商家订单-通过id删除", notes = "商家订单-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcOrderMerchantService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商家订单-批量删除")
    @ApiOperation(value = "商家订单-批量删除", notes = "商家订单-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcOrderMerchantService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "商家订单-通过id查询")
    @ApiOperation(value = "商家订单-通过id查询", notes = "商家订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcOrderMerchant> queryById(@RequestParam(name = "id", required = true) String id) {
        HcOrderMerchant hcOrderMerchant = hcOrderMerchantService.getById(id);
        if (hcOrderMerchant == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcOrderMerchant);
    }

    /**
     * 导出excel
     */
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
    @ApiOperation("商家订单页面导出")
    @RequestMapping(value = "/exportXls")
    public String exportXls(String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> list = null;

        if (StringUtils.isNotBlank(ids)) {
            list = Arrays.asList(ids.split(","));
        }

//        return hcOrderMerchantService.exportXls(sysUser.getId(), list, "");
        return hcOrderMerchantService.exportXlsNew(sysUser.getId(), list, "");
    }

    /**
     * 全局页面导出excel
     */
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
    @ApiOperation("全局页面导出excel")
    @RequestMapping(value = "/exportXlsGlobalPage")
    public String exportXlsGlobalPage(String merchantId) {
        return hcOrderMerchantService.exportXls(merchantId, null, "");
    }

    /**
     * 平台端导出订单
     */
    //@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
//    @ApiOperation("平台端导出订单")
//    @RequestMapping(value = "/platformExportXls")
//    public ModelAndView platformExportXls(HcOrderMerchant param) {
//        return hcOrderMerchantService.platformExportXls(param);
//    }

    @ApiOperation("平台端导出订单")
    @RequestMapping(value = "/platformExportXls")
    public String platformExportXls2(HcOrderMerchant param) {
        return hcOrderMerchantService.platformExportXls2(param);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_order_merchant:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return hcOrderMerchantService.importExcelByMaiKe(request);
    }

}
